<template>

	<view class="page">

		<uni-card margin='2px' style="margin-bottom: 20px; padding: 5px;">
			<view @click="openSelector">
				
			
			<mpopupHeaderItem label="经营企业名称" :value="equipment.operatorName|| '[修改]'" height="90px" />
			<mpopupHeaderItem label="经营场所" :value="equipment.operatorPlace|| '[修改]'" height="90px" />
			<mpopupHeaderItem label="仓库地址" :value="equipment.address|| '[修改]'" height="90px" />
			<mpopupHeaderItem label="经营方式" height="90px">

				<text>{{modeTypeText}}</text>
			</mpopupHeaderItem>
			<mpopupHeaderItem label="2002经营范围" :value="equipment.workLayout2002Item" height="90px" />
			<mpopupHeaderItem label="2017经营范围" :value="equipment.workLayout2017Item" height="90px" />
			<mpopupHeaderItem label="法人" :value="equipment.legalPersonName || '[修改]'" height="90px" />
			<mpopupHeaderItem label="企业负责人'" :value="equipment.enterpriseManagerName|| '[修改]'" height="90px" />
			<mpopupHeaderItem label="质量负责人" :value="equipment.qualityManagerName|| '[修改]'" height="90px" />
			<mpopupHeaderRadioItem label="申请类型" height="90px" :custom-class="'custom-align'" :show-bottom-border="true"
				:custom-style="{ padding: '20rpx' }">
				<text>{{bidTypeText}}</text>
			</mpopupHeaderRadioItem>
</view>
		</uni-card>


		<uni-card margin='2px' style="margin-bottom: 20px; padding: 5px;">
			<uni-title type="h1" align="center" title="撤销理由"></uni-title>
			<textarea @input="handleInput" v-model="equipment.remark" class="full-width-textarea" placeholder="请填写相关内容"
				:maxlength="500"></textarea>

		</uni-card>

		<view v-if="editStatus!='FLASE'" class="button-container">
			<button style="margin-bottom: 20px;" type="primary" @click="submitForm('1')">保存并提交撤销审查单</button>
			<button type="primary" @click="submitForm('0')">暂存</button>
		</view>
		
		<EnterpriseSelector tableType="3" :query="{orderType: '3', auditStatus: '1'}" type="radio"
			ref="selector" :multiple="false" @confirm="handleConfirm" @close="handleClose" />

		<uni-popup ref="verifyPopup" type="center" :is-mask-click="false" class="custom-popup">
			<uni-card class="dialog-container">
				<view class="uni-container">
					<uni-table ref="table" border stripe type="selection"
						:selectable="(row, index) => index === selectedIndex" @selection-change="selectionChange">
						<uni-tr>
							<uni-th width="80" align="center">企业名称</uni-th>
							<uni-th width="80" align="center">经营地址</uni-th>
							<uni-th width="70" align="center">工单状态</uni-th>
							<uni-th width="50" align="center">修改时间</uni-th>

						</uni-tr>
						<uni-tr v-for="(item, index) in tableData" :key="index">
							<uni-td>{{ item.operatorName }}</uni-td>
							<uni-td>
								<view class="name">{{ item.address }}</view>
							</uni-td>
							<uni-td align="center">{{ item.reviewStatus }}</uni-td>
							<uni-td align="center">{{ item.time }}</uni-td>
						</uni-tr>
					</uni-table>
					<!-- 新增按钮区块 -->
					<view class="dialog-buttons">
						<button class="cancel-btn" @click="closePopup">取消</button>
						<button class="confirm-btn" @click="handleConfirm">确定</button>
					</view>
					<view class="uni-pagination-box">
						<uni-pagination show-icon :page-size="pageSize" :current="currentPage" :total="total"
							@change="handlePageChange" />
					</view>
				</view>
			</uni-card>
		</uni-popup>
	</view>

</template>

<script>
	import signInput from "@/components/am-sign-input/am-sign-input.vue"
	import mpopupHeaderItem from "@/components/mpopup-header-item.vue"
	import mpopupHeaderRadioItem from "@/components/mpopup-header-radio-item.vue"
	import mpopupTable from "@/components/mpopup-table.vue"
	import EnterpriseSelector from "@/components/dialog/enterprise-dialog.vue"
	import {
		getformat,
		getProject,
		addMedical,
		getMedicalDict,
		medicalInfo,
		medicalUpdate
	} from '@/api/order'

	export default {
		components: {
			mpopupHeaderRadioItem,
			mpopupHeaderItem, // 需先导入组件
			mpopupTable,EnterpriseSelector
		},
		onLoad(options) {

			if (options.editStatus != null) {
				const editStatus = decodeURIComponent(options.editStatus);
				const workOrderId = decodeURIComponent(options.workOrderId);
				this.getMedicalInfo(workOrderId);
				this.editStatus = options.editStatus;
				this.workOrderId = workOrderId;
				console.log('this.equipment.workOrderId' + this.workOrderId)
			} else {
				if (options.orderData) {
					const equipment = JSON.parse(decodeURIComponent(options.orderData));
					const checkText = decodeURIComponent(options.checkText);
					const bidTypeItem = decodeURIComponent(options.bidTypeItem);
					const workOrderId = decodeURIComponent(options.workOrderId);


					console.log(this.equipment)
					this.equipment = equipment;

					this.checkText = checkText;
					this.bidTypeItem = bidTypeItem;
					this.equipment.workOrderId = workOrderId;

				}
			}
			this.getMedicalDict('2022');
			this.getMedicalDict('2017');
			this.getMedicalDict('bid_type');
			this.getMedicalDict('mode_of_operation');
		},
		computed: {
			bidTypeText() {
				const found = this.valueOptions.find(
					item => item.value == String(this.equipment.bidType) // 统一转换为字符串比较
				);
				return found ? found.text : this.bidTypeItem;
			},
			modeTypeText() {
				const found = this.valueOptions.find(
					item => item.value == String(this.equipment.modeOfOperation) // 统一转换为字符串比较
				);
				return found ? found.text : this.checkText;
			},
		},
		data() {
			return {
				operatorName: '自动生成',
				address: '自动生成',
				number: '自动生成',
				type: '自动生成',
				equipment: {
					workOrderId: '',
					remark: '',
					auditStatus: 0,
					workLayout2002Item: '',
					workLayout2017Item: '',
				},

				checkText: '',
				bidTypeItem: '',
				Item2022String: '',
				Item2017String: '',
				Item2022List: {},
				Item2017List: {},
				editStatus: 'ADD',
				valueOptions: [],
				modeOptions: [],
				workOrderId: ''
			}
		},
		methods: {
			// 打开选择器
			openSelector() {
				this.$refs.selector.open()
			},
			handleConfirm(selected) {
				this.equipment = selected
			},
			handleClose() {
				console.log('弹窗已关闭')
			},
			handleInput(e) {
				// 手动截断字符（解决部分机型兼容性问题）
				this.equipment.remark = e.target.value.slice(0, 500);
			},
			// 提交方法
			submitForm(status) {

				if (this.editStatus == 'FALSE') {
					// 处理失败情况
					uni.showToast({
						title: '当前处于查看状态',
						icon: 'none'
					});
				}

				if (this.editStatus === 'EDIT') {
					console.log("ddddd")
					this.UPDATE(status);
				}

				if (this.editStatus === 'ADD') {
					this.ADD(status);
				}



			},
			// 获取医疗器械工单详情
			async getMedicalInfo(orderId) {
				const res = await medicalInfo(orderId);
				if (res.code === 0) {
					this.equipment = res.data;
					// 确保先获取工单数据再获取字典
					await this.getMedicalDict('bid_type');
					await this.getMedicalDict('mode_of_operation');
					await this.getMedicalDict('2022');
					await this.getMedicalDict('2017');
				}
			},
			async ADD(status) {
				this.equipment.auditStatus = status;
				const res = await addMedical(this.equipment);


				if (res.code === 0) {
					// 显示成功提示
					uni.showToast({
						title: '操作成功',
						icon: 'success',
						duration: 1500
					});
			// 关闭当前页面，跳转到工单页
			this.$closeAndRedirect({
			  url: '/pages/work/history/index'
			});
				} else {
					// 处理失败情况
					uni.showToast({
						title: res.msg || '提交失败',
						icon: 'none'
					});
				}

			},

			async UPDATE(status) {
				this.equipment.auditStatus = status;
				this.equipment.workOrderId = this.workOrderId;

				const res = await medicalUpdate(this.equipment);

				if (res.code === 0) {
					// 显示成功提示
					uni.showToast({
						title: '操作成功',
						icon: 'success',
						duration: 1500
					});
					// 1.5秒后返回上一页
					setTimeout(() => {
						uni.navigateBack({
							delta: 1
						});
					}, 1500);
				} else {
					// 处理失败情况
					uni.showToast({
						title: res.msg || '提交失败',
						icon: 'none'
					});
				}

			},

			//获取字典值
			async getMedicalDict(type) {
				try {
					const res = await getMedicalDict(type)

					// 增加响应状态判断
					if (res.code === 0) {

						switch (type) {
							case '2022':
								// 正确提取 layouTtwo 字段的值
								const targetValues = new Set(
									this.equipment.workLayout2002List
									?.map(item => String(item.layouTtwo)) // 明确提取字段
									.filter(Boolean) || [] // 过滤无效值
								);

								//	const targetValues = new Set(this.equipment.workLayout2002List?.map(String) || []);
								this.Item2022List = res.data
									.filter(item => targetValues.has(String(item.value)))
									.map(item => ({
										label: item.label,
										value: item.value
									}));


									this.equipment.workLayout2002Item = this.Item2022List
									.map(item => `${String(item.label)}`) // 模板字符串拼接
									//	.map(item => `${String(item.value)}${String(item.label)}`) // 模板字符串拼接
									.join(','); // 用逗号连接成字符串
								console.log('this.Item2022String', this.Item2022String)
								break;
							case '2017':
								const targetValues2 = new Set(
									this.equipment.workLayout2017List
									?.map(item => String(item.layoutSeven)) // 明确提取字段
									.filter(Boolean) || [] // 过滤无效值
								);

								this.Item2017List = res.data
									.filter(item => targetValues2.has(String(item.value)))
									.map(item => ({
										label: item.label,
										value: item.value
									}));
								this.equipment.workLayout2017Item = this.Item2017List
									.filter(item => item?.value && item?.label) // 过滤空值
									.map(item => `${String(item.label)}`) // 模板字符串拼接
									.join(', ');

								console.log('this.Item2017String', this.Item2017String)
								break;

							case 'bid_type':
								this.valueOptions = res.data.map(item => ({
									text: item.label,
									value: String(item.value) // 确保字典值转为字符串
								}));
								break;
							case 'mode_of_operation':
								this.modeOptions = res.data.map(item => ({
									text: item.label,
									value: String(item.value) // 确保字典值转为字符串
								}));


								break;

							default:
								return;
						}
					} else {
						throw new Error(res?.data?.msg || '接口返回异常')
					}

				} catch (error) {
					uni.showToast({
						title: error.message || '获取分类失败',
						icon: 'none',
						duration: 2000
					})
				}
			},
		}
	}
</script>

<style>
	/* 网页容器样式 */
	.page {
		flex: 1;
		background-color: #e9f1fe;
		padding: 20px;
		box-sizing: border-box;
	}


	.full-width-textarea {
		width: 100%;
		background-color: #e9f1fe;
		height: 400rpx;
		padding: 20rpx;
		box-sizing: border-box;
		border: 1rpx solid #e5e5e5;
		border-radius: 8rpx;
		line-height: 1.6;
	}


	.uni-column {
		padding: 20px;
		background-color: #e9f1fe;
		height: 300px;
		margin-top: 10px;
		margin-bottom: 10%;
		border-radius: 10px;
	}
</style>